import GetLocation from '@/components/GetLocation/';
import pEdit from '@/images/common/edite.png';
import pRightIcon from '@/orderSubPack/images/confirmOrder/right-icon.png';
import { Image, Input, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { DistributionWay } from '../constant';
import AddressSelect from '@/pages/mainPages/addressSelect/index';
import { regeo } from '@/dataTransfer/address';
import styles from './index.module.scss';

function protectMobile(mobile) {
  if (!mobile) {
    return '';
  }
  return mobile.replace(/(\d{3,3})\d{4,4}(\d+)/, '$1****$2');
}

const NoAddress = ({ handleAddrSel }) => {
  return (
    <View className="flex-column" onClick={handleAddrSel}>
      <View className="line-2">
        <View className="address-detail omit">请新建收货地址</View>
        <Image className="right-icon" src={pRightIcon} />
      </View>
      <View className="var-flex line-4">
        <View>配送方式</View>
        <View>快递</View>
      </View>
    </View>
  );
};

const UserAddressView = ({ value, handleAddrSel }) => {
  const { contactName, mobile, address1, address2 } = value ?? {};

  if (!contactName) {
    return <NoAddress handleAddrSel={handleAddrSel} />;
  }

  return (
    <View className="flex-column" onClick={handleAddrSel}>
      <View className="address omit">{address1 ?? ''}</View>

      <View className="line-2">
        <View className="address-detail omit">{address2 ?? ''}</View>

        <Image className="right-icon" src={pRightIcon} />
      </View>

      <View className="line-3">
        <View className="contact-name">{contactName}</View>
        <View className="phone">{protectMobile(mobile)}</View>
      </View>

      <View className="var-flex line-4">
        <View>配送方式</View>
        <View>快递</View>
      </View>
    </View>
  );
};

const StoreAddressView = ({ orgInfo, value, onChange }) => {
  const [curMobile, setCurMobile] = useState(null);
  const [editMobile, setEditMobile] = useState(false);

  const updateMobile = (e) => {
    let v = e.detail.value;
    let reg = /^[1][3,4,5,7,8][0-9]{9}$/;

    setCurMobile(v);

    if (reg.test(v)) {
      setEditMobile(false);
      // 回传
      onChange({
        ...value,
        mobile: v,
      });
    } else {
      Taro.showToast({ title: '手机号不正确', icon: 'none' });
    }
  };

  const showMap = () => {
    // if (Object.keys(orgInfo).length) {
    //   // TODO: h5端仅在微信公众号中支持 API openLocation
    //   Taro.openLocation({
    //     latitude: Number(orgInfo.orgLatitude),
    //     longitude: Number(orgInfo.orgLongtitude),
    //     scale: 15,
    //     name: orgInfo.orgName || '',
    //     address: orgInfo.orgAddress || '',
    //   });
    // }
  };

  // 变更 手机号
  useEffect(() => {
    setCurMobile(value?.mobile);
  }, [value]);

  return (
    <View className="flex-column">
      <View className="store-info flex-row-spaceBetween-center">
        <View className="store-name omit">{orgInfo?.orgName}</View>
        <View className="store-position flex-row-spaceBetween-center" onClick={showMap}>
          <View className="txt">距离你{orgInfo?.distanceMeter}</View>
          <Image className="icon" src={pRightIcon} />
        </View>
      </View>

      <View className="user-info flex-row-spaceBetween-center">
        <View className="txt">预留电话</View>

        <View className="flex-row-spaceBetween-center">
          {editMobile ? (
            <View className="mobile">
              <Input
                className="edit"
                type="text"
                value={curMobile}
                maxLength="11"
                focus
                onBlur={updateMobile}
              />
            </View>
          ) : (
            <View className="mobile">{protectMobile(curMobile)}</View>
          )}

          <Image
            className="icon"
            src={pEdit}
            onClick={() => {
              setEditMobile(true);
            }}
          />
        </View>
      </View>
    </View>
  );
};

const AddressView = ({
  // 自带
  dispatch,
  orgInfoLocation,

  // 组件传递
  merchantId,
  orgId,
  distributionWay,
  distributionWayList,

  value,
  onChange,

  className = '',
}) => {
  const [location, setLocation] = useState();

  const [isShowAddressSelect, setIsShowAddressSelect] = useState(false);
  const [curLocation, setCurLocation] = useState();
  const handleAddrSel = () => {
    setIsShowAddressSelect(true)
    return;
    let url = '/giftCardSubPack/address/index?from=confirmOrder';
    if (distributionWay === DistributionWay.rider) {
      url += '&orgId=' + orgId + '&merchantId=' + merchantId;
    }
    Taro.navigateTo({ url });
  };

  const getLocationAddr = (location) => {
    regeo(location)
      .then(({ address, adcode }) => {
        dispatch({
          type: 'productCar/setLocationAddress',
          payload: { ...location, address: address },
        });

        setCurLocation({ ...location, adCode: adcode, fullAddress: address });
      })
      .catch(console.warn);
  };
  const updateCurLocation = (location) => {
    if (!location) {
      return;
    }

    // 服务器的地址
    if (location.addressId) {
      setCurLocation(location);
      return;
    }

    // 由经纬度, 转换 adCode
    if (!location.adCode && location.latitude) {
      getLocationAddr(location);
    }
  };
  // 获取 自提时店铺信息
  useEffect(() => {
    if (distributionWay !== DistributionWay.selfHelp || !location) {
      return;
    }

    if (orgInfoLocation?.orgId !== orgId || orgInfoLocation?.merchantId !== merchantId) {
      dispatch({
        type: 'otherApi/getOrgInfoWithLocationModel',
        payload: {
          merchantId: merchantId,
          orgId: orgId,
          longitude: location.longitude,
          latitude: location.latitude,
        },
      });
    }
  }, [distributionWay, location]);

  // 回传 地址信息
  useEffect(() => {
    if (curLocation) {
      // onChange(curLocation);
    }
  }, [curLocation]);

  if (!distributionWayList?.length) {
    return null;
  }

  return (
    <View
      className={classNames(`${styles.AddressView} ${className}`, {
        'multi-way': distributionWayList?.length >= 2,
      })}
    >
      {/* 自提, 计算当前位置 */}
      {distributionWay === DistributionWay.selfHelp && <GetLocation handleLocation={setLocation} />}

      {/* 自提 */}
      {distributionWay === DistributionWay.selfHelp && (
        <StoreAddressView
          {...{
            orgInfo: orgInfoLocation,
            value,
            onChange,
          }}
        />
      )}

      {/* 快递 / 骑手配送 */}
      {(distributionWay === DistributionWay.express ||
        distributionWay === DistributionWay.rider) && (
        <UserAddressView {...{ value, onChange, handleAddrSel }} />
      )}
      
      <AddressSelect
        isOpened={isShowAddressSelect}
        handleClose={(sa) => {
          setIsShowAddressSelect(false);

          // 回传了选择的地址, 则进行更新
          if (sa) {
            const { id, latitude, longitude, address, houseNumber } = sa;
            onChange(sa)
            updateCurLocation({
              latitude,
              longitude,
              addressId: id,
              fullAddress: address + houseNumber,
            });
          }
        }}
      />
    </View>
  );
};

export default connect(({ loading, order, otherApi }) => ({
  loading,

  orgDistributionWay: order.orgDistributionWay,
  orgInfoLocation: otherApi.orgInfoLocation,
}))(AddressView);
